<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    width="1000px"
    title="配置字典"
    @ok="handleSubmit"
  >
    <BasicTable @register="registerTable">
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)"/>
      </template>
    </BasicTable>
    <a-button block class="mt-5" type="dashed" @click="handleAdd"> 新增字典数据 </a-button>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    ActionItem,
    EditRecordRow,
  } from '/@/components/Table';
  import { dictColumns } from './column.data';
  import { getAllDictList, saveDictList, updateDict, removeDict } from '/@/api/free/dict';
  import {cloneDeep} from "lodash-es";

  export default defineComponent({
    name: 'DictModal',
    components: { BasicModal, BasicTable, TableAction },
    emits: ['success', 'register'],
    setup() {
      const [registerTable, { getDataSource, setTableData, deleteTableDataRecord, insertTableDataRecord }] = useTable({
        columns: dictColumns,
        showIndexColumn: false,
        maxHeight: 400,
        dataSource: [],
        rowKey: 'id',
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        pagination: false,
      });

      const columnId = ref('');
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({
          confirmLoading: false,
          showOkBtn: false,
          cancelText: '关闭',
          closeFunc: () =>
            new Promise((resolve) => {
              resolve(true);
            }),
        });
        columnId.value = data.columnId;

        let dictList = await getAllDictList(unref(columnId));
        if (dictList.length == 0) {
          handleAdd();
        } else {
          setTableData(dictList);
        }
      });

      function handleEdit(record: EditRecordRow) {
        record.onEdit?.(true);
      }

      function handleDelete({ id }) {
        if (id) {
          removeDict(id).then(() => {
            deleteTableDataRecord(id);
          });
        } else {
          deleteTableDataRecord(id);
        }
      }

      function handleSubmit(record: EditRecordRow) {
        let data = cloneDeep(record.editValueRefs);
        if (!data) return;
        console.log(data);
        data.columnId = record.columnId;
        if (record.id) {
          data.id = record.id;
          updateDict(data).then(() => record.onEdit?.(false, true));
        } else {
          saveDictList(data).then((id) => {
            record.id = id;
            record.dictLabel = data.dictLabel;
            record.dictValue = data.dictValue;
            record.remark = data.remark;
            record.onEdit?.(false, true);
          });
        }
      }

      function handleAdd() {
        insertTableDataRecord({
          id: '',
          dictLabel: '',
          dictValue: '',
          remark: '',
          columnId: unref(columnId),
        });
        setTimeout(() => {
          getDataSource()
            .filter((item) => !item.id)
            .forEach((item) => item.onEdit?.(true));
        }, 500);
      }

      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        const actions: ActionItem[] = [];
        actions.push({
          icon: 'ant-design:check-square-outlined',
          disabled: record.isDefault,
          tooltip: '设为默认',
          onClick: handleAdd.bind(null, record),
        });

        if (record.editable) {
          actions.push({
            icon: 'ant-design:check-outlined',
            tooltip: '保存',
            onClick: handleSubmit.bind(null, record, column),
          });
        } else {
          actions.push({
            icon: 'clarity:note-edit-line',
            tooltip: '编辑',
            onClick: handleEdit.bind(null, record),
          });
        }
        actions.push({
          icon: 'ant-design:delete-outlined',
          tooltip: '删除',
          onClick: handleDelete.bind(null, record),
        });
        return actions;
      }

      return {
        registerModal,
        registerTable,
        handleAdd,
        getDataSource,
        handleEdit,
        handleDelete,
        handleSubmit,
        createActions,
      };
    },
  });
</script>
